package com.voice.server.controller;

import com.voice.server.authentication.TokenAuthentication;
import com.voice.server.entity.AppToken;
import com.voice.server.exception.SystemException;
import com.voice.server.service.AppTokenService;
import com.wangjiacai.utils.output.ResultVO;
import com.wangjiacai.utils.utils.ResultVOUtil;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/app")
public class AppTokenController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private AppTokenService appTokenService;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/appKey")
    public ResultVO getAppKey(@RequestHeader("token")String token){
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        AppToken appToken=appTokenService.findByUserId(userId);
        return ResultVOUtil.success(appToken);
    }

    @PutMapping("/pushUrl")
    public ResultVO putPushUrl(@RequestHeader("token")String token,String pushUrl){
        if(StringUtils.isEmpty(pushUrl)||! pushUrl.matches("(http|https):\\/\\/[^\\s]+\\.[^\\s]+")) throw new SystemException("url格式不正确");
        try{
            restTemplate.postForEntity(pushUrl,null,Object.class);
        }catch (Exception e){
            throw new SystemException("修改失败，当前只支持Http Status Code=200的url");
        }
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        appTokenService.updatePushUrl(userId,pushUrl);
        return ResultVOUtil.success();
    }

}
